#define _CRT_SECURE_NO_WARNINGS 1
#include <vector>
#include <iostream>
#include <queue>
using namespace std;
using pii = pair<int, int>;
int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
int m = 0, n = 0;
class Solution {
public:
    int bfs(vector<vector<int>>& forest, int stari, int starj, int target, int* tari, int* tarj)
    {
        vector<vector<bool>> sta(m, vector<bool>(n, false));
        sta[stari][starj] = true;
        int count = 0;
        queue<pii> q;
        q.push({ stari,starj });
        while (!q.empty())
        {
            ++count;
            int cnt = q.size();
            //cout<<"qsize="<<q.size()<<endl;
            while (cnt--)
            {
                int a = q.front().first;
                int b = q.front().second;
                q.pop();
                for (int i = 0;i < 4;i++)
                {
                    int x = a + dx[i], y = b + dy[i];
                    if (x >= 0 && x < m && y >= 0 && y < n && forest[x][y] >= 1 && sta[x][y] == false)
                    {
                        if (forest[x][y] == target)
                        {
                            *tari = x;
                            *tarj = y;
                            return count;
                        }
                        q.push({ x,y });
                        sta[x][y] = true;
                    }
                }
            }
        }
        return -1;
    }
    int cutOffTree(vector<vector<int>>& forest)
    {
        m = forest.size();
        n = forest[0].size();
        priority_queue<int, vector<int>, greater<int>> pq;
        for (auto a : forest)
        {
            for (auto b : a)
            {
                if (b > 1) pq.push(b);
            }
        }
        if (pq.top() == forest[0][0]) pq.pop();
        int count = 0;
        int x = 0, y = 0;
        while (!pq.empty())
        {
            int t = pq.top();
            cout << t << endl;
            pq.pop();
            int n = bfs(forest, x, y, t, &x, &y);
            cout << n << endl;
            forest[x][y] = 1;
            if (n == -1) return -1;
            count += n;
        }
        return count;
    }
};